import dayjs from "dayjs";
/**
 * @auth NoahLiu
 * @team 星城前端团队
 * @description 缓存操作，会打印缓存日志，自动将缓存专户为 type value 接口，能够免去存入之前的字符化，以及取出之后的序列化
 */
export default {
  get(key, defaultRes = {}) {
    let storageRes = uni.getStorageInfoSync();
    if (storageRes.keys.includes(key)) {
      let newVal = uni.getStorageSync(key);
      try {
        newVal = JSON.parse(newVal);
      } catch (error) {
        console.error("uniStorage get parse Obj:", key, error);
      }
      if (newVal && typeof newVal === "object") {
        let data = newVal;
        let value: any = newVal;
        switch (data.type) {
          case "string":
            value = data.value;
            break;
          case "number":
            value = parseFloat(data.value);
            break;
          case "boolean":
            value = data.value === "true";
            break;
          case "date":
            value = dayjs(data.value);
            break;
          case "undefined":
            value = undefined;
            break;
          default:
            try {
              value = JSON.parse(data.value);
            } catch (error) {
              console.error("uniStorage get parse value:", key, error);
              value = data.value;
            }
            break;
        }
        return value;
      } else {
        if (newVal) {
          return newVal;
        } else {
          return defaultRes;
        }
      }
    } else {
      return defaultRes;
    }
  },
  set(key, val) {
    let data = {
      value: "",
      type: "",
    };
    if (typeof val !== "object") {
      data.value = val.toString();
      data.type = typeof val;
    } else {
      let type = Object.prototype.toString.call(val).replace("[object ", "").replace("]", "").toLowerCase();
      switch (type) {
        case "date":
          val = dayjs(val).format("YYYY-MM-DD HH:mm:ss:sss");
          data.type = "date";
          break;
        default:
          try {
            val = JSON.stringify(val);
          } catch (error) {
            console.error("uniStorage set stringify:", key, error);
          }
          data.type = "object";
          break;
      }
      data.value = val;
    }
    uni.setStorageSync(key, JSON.stringify(data));
  },
};
